<template>
    <div class="app-container">
      <el-card class="box-card">
        <el-button type="primary" @click="handleCreate">新增</el-button>
        <el-table
          ref="multipleTable"
          v-loading="loading"
          :data="tableData"
          border
          class="mt-3"
          stripe
          style="width: 100%"
          tooltip-effect="dark"
        >
          <el-table-column label="序号" type="index" :index="indexMethod" prop="unit_price" width="80px"></el-table-column>
          <el-table-column label="上传时间" prop="created_at"></el-table-column>
          <el-table-column label="横图图片" prop="picture">
            <template slot-scope="{row}">
                <el-popover placement="left" width="220" trigger="hover">
                    <img :src="row.picture" alt="" style="max-width: 250px;max-height: 250px">
                    <img slot="reference" :src="row.picture" alt="" style="height: 100px">
                </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="使用状态" prop="state">
            <template slot-scope="{row}">
                <span>{{row.state === 0 ? '禁用' : row.state === 1 ? '测试中' : '启用'}}</span>
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="300px">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                @click="handleUpdate(scope.row)"
              >编辑
              </el-button>
              
              <el-button
                size="mini"
                type="text"
                @click="handleStatus(scope.row)"
              >状态
              </el-button>

              <el-button
                size="mini"
                type="text"
                @click="handleDelBanners(scope.row)"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
  
        <!-- 分页 -->
        <cus-pagination
          v-show="total > 0"
          :limit.sync="listQuery.perPage"
          :page.sync="listQuery.page"
          :total="total"
          @pagination="getTableData"
        />
      </el-card>
  
      <el-dialog
        :visible.sync="dialogVisible"
        title="横幅状态"
        width="30%"
        @close="closeDialog('form')"
      >
        <el-form ref="form" :inline="false" :model="formData" :rules="rules" label-width="120px" size="normal">
          <el-form-item label="横幅状态" prop="state">
            <el-select v-model="formData.state" >
                <el-option
                  v-for="item in statusList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
          </el-form-item>
          
        </el-form>
  
        <span slot="footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleupdateBannersStatus">确定</el-button>
        </span>
      </el-dialog>

      <el-dialog
      v-dialogDrag
      :title="titleMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      @close="handleDialogClose('editRulesForm')"
      width="40%"
    >
      <el-form ref="editRulesForm" :model="editRulesForm" :rules="editRulesFormRules" class="demo-ruleForm" label-width="120px">
        
        <el-form-item label="横幅图片" prop="picture">
          <el-upload
            ref="upload"
            :auto-upload="true"
            :before-upload="beforeAvatarUpload"
            :file-list="specialFlagBigList"
            :http-request="customizeUpload"
            :on-change="handleChangePic"
            :on-remove="handleSpecialFlagBigRemove"
            :on-success="handleSpecialFlagBigSuccess"
            action=""
            class="upload-demo"
            list-type="picture"
          >
            <el-button slot="trigger" size="small" type="primary">上传横幅图片</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-radio-group v-model="editRulesForm.state">
            <el-radio :label="2">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
            <el-radio :label="1">测试</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item>
          <el-button @click="dialogFormVisible = false">返回</el-button>
          <el-button type="primary" @click="submitForm('editRulesForm')">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  
    </div>
</template>
  
<script>
    import { buildBannersStatus, buildBannersList, buildBannersAdd, buildBannersDelete } from '@/api/guardActivity'
  
  export default {
        name: 'bannerList',
        components: {},
        data() {
        return {
            specialFlagBigList: [],
            dialogVisible: false,
            dialogFormVisible: false,
            formData: {
                state: undefined
            },
            rules: {
                state: [{ required: true, message: '请选择横幅状态', trigger: 'blur' }]
            },
            editRulesForm: {
                picture: '',
                state: ''
            },
            editRulesFormRules: {
                state: [{ required: true, message: '请选择横幅状态', trigger: 'blur' }],
                picture: [{ required: true, message: '请上传横幅图片', trigger: 'blur' }],
            },
            rowId: '',
            loading: false,
            tableData: [],
            listQuery: {
                page: 1,
                perPage: 10
            },
            total: 1,
            statusList: [
                {
                    label: '启用',
                    value: 2
                },
                {
                    label: '测试',
                    value: 1
                },
                {
                    label: '禁用',
                    value: 0
                }
            ],
            dialogStatus: '',
            titleMap: {
                update: '编辑',
                create: '新增'
            },
        }
    },
    created() {
        this.getTableData()
    },
    methods: {
        indexMethod(index) {
			return this.tableData.length - index
		},
        submitForm() {
            this.$refs['editRulesForm'].validate(valid => {
                if (valid) {
                    this.handleEditOrAddBanners(this.editRulesForm)
                }
            })
        },
    
        // 网络请求
        /**
         * getTableData
         * @desc 获取表格数据
         */
        async getTableData() {
            this.loading = true
            for (let key in this.listQuery) {
                this.listQuery[key] = this.listQuery[key] === '' ? undefined : this.listQuery[key]
            }
            const detail = await buildBannersList(this.listQuery)
            if (detail.code === 200) {
                this.tableData = detail.data.data
                this.listQuery.page = detail.data.current_page
                this.total = detail.data.total
                this.listQuery.perPage = Number(detail.data.per_page)
            }
            this.loading = false
    
        },
        closeDialog(form) {
            if (this.$refs[form]) {
                this.$refs[form].clearValidate() // 清除整个表单的校验
                this.$refs[form].resetFields() // 清除整个表单的校验
            }
        },
        handleCheck(row) {
            this.$router.push({
                path: 'crystalDeatils',
                query: {
                    rowId: row.$index
                }
            })
        },
        handleStatus(row) {
            this.dialogVisible = true
            this.rowId = row.id
            this.formData = JSON.parse(JSON.stringify(row))
        },
        handleupdateBannersStatus() {
            this.$refs['form'].validate(valid => {
                if (valid) {
                    if(this.formData.state === 1) {
                        this.$prompt('请输入测试人员ID：', '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            inputPattern: /^[0-9]/,
                            inputErrorMessage: '请输入正确的测试人员ID'
                        }).then(({value}) => {
                            buildBannersStatus({
                                state: this.formData.state,
                                test_users: value,
                                id: this.formData.id
                            },this.rowId).then(res => {
                                if(res.code === 200) {
                                    this.dialogVisible = false
                                    this.getTableData()
                                }
                            })
                        }).catch(() => {
                            this.$message({
                                type: 'info',
                                message: '取消输入'
                            });       
                        });
                    }else {
                        buildBannersStatus({
                            state: this.formData.state,
                            id: this.formData.id
                        }).then(res => {
                            if(res.code === 200) {
                                this.dialogVisible = false
                                this.$message({
                                    type: 'success',
                                    message: '操作成功'
                                })
                                this.getTableData()
                            }
                        })
                    }
                    
                    
                } else {
                    return false
                }
            })
        },
        // 点击新增
        handleCreate() {
            this.editRulesForm = {
                picture: '',
                state: undefined,
                id: undefined
            }
            this.dialogStatus = 'create'
            this.dialogFormVisible = true
        },
        // 点击编辑
        handleUpdate(row) {
            console.log(row)
            this.row_id = row.id
            this.editRulesForm = {
                id: row.id,
                picture: row.picture,
                state: row.state,
            }
            this.specialFlagBigList = [{ url: row.picture }]
            this.dialogStatus = 'update'
            this.dialogFormVisible = true
        },
        handleSpecialFlagBigSuccess() {
            this.editRulesForm.picture = this.ossLastImgUrl
            this.specialFlagBigList = [{ url: this.ossLastImgUrl }]
        },
        handleSpecialFlagBigRemove() {
            this.specialFlagBigList = []
        },
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/webp' || file.type === 'image/gif'
            const isLt2M = file.size / 1024 / 1024 < 2

            if (!isJPG) {
                this.$message.error('请上传JPG/PNG格式的图片!')
            }
            if (!isLt2M) {
                this.$message.error('上传图片大小不能超过 2MB!')
            }
            return isJPG && isLt2M
        },
        handleChangePic(fileList) {
            if (fileList.length > 1) {
                fileList.splice(0, 1)
            }
        },
        handleDialogClose(formName) {
            if (this.$refs[formName]) {
                this.$refs[formName].clearValidate() // 清除整个表单的校验
            }
            this.editRulesForm = {
                picture: '',
                state: ''
            }
        },
        handleEditOrAddBanners(data) {
            buildBannersAdd(data).then(res => {
                if(res.code === 200) {
                    this.$message({
                        type: 'success',
                        message: '操作成功'
                    })
                    this.dialogFormVisible = false
                    this.editRulesForm = {
                        id: undefined,
                        picture: '',
                        state: undefined
                    }
                    this.getTableData()
                }
            })
        },
        // 删除
        handleDelBanners(data) {
            console.log(data)
            this.$confirm('此操作将永久删除该横幅, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                buildBannersDelete({
                    id: data.id
                }).then(res => {
                    if(res.code === 200) {
                        this.$message({
                            type: 'success',
                            message: '操作成功'
                        })
                        this.dialogFormVisible = false
                        this.editRulesForm = {
                            id: undefined,
                            picture: '',
                            state: undefined
                        }
                        this.getTableData()
                    }
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        }
    }
  }
</script>
  
<style lang="scss" scoped>

</style>
  